package fr.mma.scrumm.resources;

import java.util.logging.Level;
import java.util.logging.Logger;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.QueryParam;

import com.google.gson.Gson;
import com.sun.jersey.api.view.Viewable;

import fr.mma.scrumm.dao.Dao;
import fr.mma.scrumm.factory.SprintFactory;
import fr.mma.scrumm.model.Sprint;

@Path("/sprint")
public class SprintResource {
	Logger log = Logger.getLogger(SprintResource.class.getName());
	
	SprintFactory sprintFactory = new SprintFactory();
	
	Dao<Sprint> dao = new Dao<Sprint>(Sprint.class);
	
	Gson gson= new Gson();
	
	@POST
	@Consumes("application/json")
	@Produces("text/plain")
	public String write(String json){
		Sprint sprint = gson.fromJson(json, Sprint.class);
		dao.save(sprint);
		return sprintFactory.build(sprint).getUrl();
	}
	
	@GET
	@Path("{id}")
	public Viewable getSpringById(@PathParam("id") String id) {
		Long key = Long.parseLong(id);
		Sprint sprint = dao.getByKey(key);
		return new Viewable("/SprintResource.jsp", sprintFactory.build(sprint));
	} 

	@GET
	@Path("/json")
	@Produces("application/json")
	public String getAll(@QueryParam("filter")String filter){
		log.log(Level.INFO, filter);
		return gson.toJson(sprintFactory.build(dao.getAll()));
	}

	@GET
	@Path("{id}/json")
	@Produces("application/json")
	public String getSpringByIdJSON(@PathParam("id") String id) {
		Long key = Long.parseLong(id);
		Sprint sprint = dao.getByKey(key);
		return gson.toJson(sprintFactory.build(sprint));
	}
}
